<template>
  <el-card>
    <el-form inline size="small" @submit.native.prevent>
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="searchUser"
        >
          查询
        </el-button>
        <el-button size="small"> 清空 </el-button>
      </el-form-item>
    </el-form>
    <div class="mt-20">
      <el-button
        type="primary"
        size="small"
        @click="addUser"
        v-permission="'btn.User.add'"
      >
        添加
      </el-button>
      <el-button
        type="danger"
        disabled
        size="small"
        v-permission="'btn.User.remove'"
        >批量删除</el-button
      >
    </div>
    <el-table :data="tabelData" border class="my-20" v-loading="isLoading">
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" width="80px" align="center">
      </el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="用户昵称" prop="nickName"></el-table-column>
      <el-table-column label="角色列表">
        <template #default="{ row }">
          <el-tag
            v-for="(item, index) in row.roleName.split(',')"
            :key="index"
            size="mini"
            class="user-tag"
            v-show="!!item"
          >
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
      <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
      <el-table-column label="操作" width="200px" align="center" fixed="right">
        <template #default="{ row }">
          <el-button
            type="info"
            icon="el-icon-s-custom"
            size="mini"
            title="分配角色"
            @click="assignRole(row)"
            v-permission="'btn.User.assgin'"
          ></el-button>
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            title="编辑用户"
            v-permission="'btn.User.update'"
            @click="editUser(row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            title="删除用户"
            @click="delUser(row)"
            v-permission="`btn.User.remove`"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[3, 5, 10, 15]"
      :page-size="100"
      layout=" prev, pager, next, jumper, sizes, total"
      :total="pagination.total"
    />

    <!-- 添加用户的弹出框 -->
    <el-dialog
      :title="addUserForm.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogVisible"
      top="0"
    >
      <el-form
        label-width="120px"
        size="small"
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="addUserForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!addUserForm.id">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的弹出框 -->
    <el-dialog :title="'设置角色'" :visible.sync="dialogVisible2" top="0">
      <el-form label-width="120px" size="small" ref="ruleForm">
        <el-form-item label="用户名">
          <el-input :placeholder="userName" disabled></el-input>
        </el-form-item>

        <el-form-item
          label="角色列表"
          v-loading="isLoading2"
          element-loading-text="加载中"
          element-loading-spinner="el-icon-loading"
        >
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>

          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="roles.assignRoles"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="role in roles.allRolesList"
              :key="role.id"
              :label="role.id"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false" size="small">
          取 消
        </el-button>
        <el-button type="primary" @click="realAsssingRole" size="small">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getUserInfoList,
  saveUserApi,
  updateUserApi,
  getUserRolesApi,
  assignRolesApi,
  delUserApi
} from '@/api/acl/user'
import { mapGetters } from 'vuex'
export default {
  name: 'User',
  data() {
    const validUsername = (rule, value, callback) => {
      if (rule.fullField === 'username') {
        if (!value.length) {
          callback(new Error('请输入用户名'))
          return
        }
        if (value.length < 4) {
          callback(new Error('用户名不能小于4位'))
          return
        }
        callback()
      } else if (rule.fullField === 'nickName') {
        if (!value.length) {
          callback(new Error('请输入用户昵称'))
          return
        }
        callback()
      } else if (rule.fullField === 'password') {
        if (!value.length) {
          callback(new Error('请输入密码'))
          return
        }
        if (value.length < 6) {
          callback(new Error('密码不能小于6位'))
          return
        }
        callback()
      }
    }
    return {
      searchName: '',
      isLoading: false,
      dialogVisible: false,
      dialogVisible2: false,
      isLoading2: false,
      pagination: {
        page: 1,
        limit: 3,
        total: 3
      },
      tabelData: [],
      // 添加用户的表单
      addUserForm: {
        username: '',
        nickName: '',
        password: '',
        id: undefined
      },
      // 表单验证
      addUserFormRules: {
        username: [{ required: true, validator: validUsername }],
        nickName: [{ required: true, validator: validUsername }],
        password: [{ required: true, validator: validUsername }]
      },
      checkAll: false,
      isIndeterminate: true,
      userId: undefined,
      userName: '',
      roles: {
        allRolesList: [],
        assignRoles: []
      }
    }
  },
  mounted() {
    this.getLUserInfo()
  },
  methods: {
    // 删除用户
    async delUser({ id }) {
      if (!confirm('确定删除？')) return
      await delUserApi(id)
      this.$message.success('删除成功')
      this.getLUserInfo()
    },
    // 条件搜索
    searchUser() {
      this.getLUserInfo()
    },
    // 全选
    handleCheckAllChange(val) {
      this.roles.assignRoles = val
        ? this.roles.allRolesList.map((role) => role.id)
        : []
      this.isIndeterminate = false
    },
    // 单选框
    handleCheckedRolesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.roles.allRolesList.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roles.allRolesList.length
    },
    // 提交表单添加用户的表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.addUserForm.id) {
            await updateUserApi(this.addUserForm)
            this.$message.success('修改用户成功')
          } else {
            await saveUserApi(this.addUserForm)
            this.$message.success('添加用户成功')
          }
          this.getLUserInfo()
          this.dialogVisible = false
        }
      })
    },
    // 给用户分配角色=== 1. 获取用户角色
    async assignRole(row) {
      console.log(row)
      this.dialogVisible2 = true
      this.userName = row.username
      this.userId = row.id
      this.isLoading2 = true
      const res = await getUserRolesApi(row.id)
      this.roles.assignRoles = res.data.assignRoles.map((role) => role.id)
      this.roles.allRolesList = res.data.allRolesList
      this.checkAll =
        this.roles.allRolesList.length === this.roles.assignRoles.length
      this.isIndeterminate = !!this.roles.assignRoles.length && !this.checkAll
      this.isLoading2 = false
    },
    // 给用户分配角色=== 2. 分配角色
    async realAsssingRole() {
      await assignRolesApi(this.userId, this.roles.assignRoles)
      this.$message.success('分配成功')
      this.dialogVisible2 = false
      this.getLUserInfo()
    },
    // 添加用户
    addUser() {
      this.addUserForm.id = undefined
      this.addUserForm.username = ''
      this.addUserForm.nickName = ''
      this.addUserForm.password = ''
      this.dialogVisible = true
    },
    // 编辑用户
    editUser(row) {
      this.addUserForm.username = row.username
      this.addUserForm.nickName = row.nickName
      this.addUserForm.id = row.id
      this.dialogVisible = true
    },
    // 清除表单校验
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleSizeChange(size) {
      this.pagination.limit = size
      this.getLUserInfo()
    },
    // 切换页码
    handleCurrentChange(page) {
      this.pagination.page = page
      this.getLUserInfo()
    },
    // 封装请求数据
    async getLUserInfo() {
      this.isLoading = true
      const res = await getUserInfoList(
        this.pagination.page,
        this.pagination.limit,
        this.searchName
      )
      this.tabelData = res.data.items
      this.pagination.total = res.data.total
      this.isLoading = false
    }
  },
  computed: {
    ...mapGetters(['buttons'])
  }
}
</script>

<style>
.mt-20 {
  margin-top: 20px;
}
.my-20 {
  margin: 20px 0;
}
.user-tag {
  margin: 0 3px;
}
</style>
